import axios from "axios";
import qs from 'qs'

var url = "";

// 创建axios实例
const service = axios.create({
    baseURL: url, // api的base_url
    timeout: 30000, // 请求超时时间 30000
    headers: {
        // 'Content-Type': 'application/x-www-form-urlencoded'
        'Content-Type': 'application/json;charset=utf-8',
        "X-Requested-With": "XMLHttpRequest"
    }
});

// request拦截器
service.interceptors.request.use(
    config => {
        console.log(config, "请求参数");

        config.headers['token'] = localStorage.getItem('token');
        // config.headers['Content-Type'] = config.headers['Content-Type'] || 'application/x-www-form-urlencoded';
        // config.data = JSON.stringify(config.data);
        // config.data = qs.stringify(config.data);

        //上传特殊化
        // if (config.headers['Content-Type'] != "multipart/form-data") {
        //     config.data = qs.stringify(config.data);
        // }

        return config;
    },
    error => {
        Promise.reject(error);
    }
);

// respone拦截器
service.interceptors.response.use(
    response => {

        console.log(response, "===response====");

        const result = response.data;

        if (result.success) {
            return Promise.resolve(result.data);
        }

        //特殊错误码处理
        switch (result.resultCode) {
            case 100010:
                errMsg = "需要权限,请先登陆";
                window.location.href = "./login.html";
                break;
            default:
                errMsg = result.resultMsg;
                break;
        }


        return Promise.reject(result);
    },
    error => {
        return Promise.reject(error);
    }
);

export default service;
